﻿using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Filters;
using WMS_Api.Models;

namespace WMS_Api.App_Start
{
    public class MesWebApiExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            if (context.Exception is NotImplementedException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotImplemented)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(new MesApiResult()
                    {
                        code = (int)ResultCode.MesError,
                        msg = context.Exception.Message
                    }), Encoding.UTF8, "application/json")
                });
            }
            else if (context.Exception is TimeoutException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.RequestTimeout)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(new MesApiResult()
                    {
                        code = (int)ResultCode.MesError,
                        msg = context.Exception.Message
                    }), Encoding.UTF8, "application/json")
                });
            }
            else
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(new MesApiResult()
                    {
                        code = (int)ResultCode.MesError,
                        msg = context.Exception.Message
                    }), Encoding.UTF8, "application/json")
                });
            }
        }
    }
}
